//
//  DBLoginViewController.swift
//  DBCA
//
//  Created by mugua on 2024/7/5.
//

import UIKit

class DBLoginViewController: DBBaseViewController {
    
    let disposeBag = DisposeBag()
    let countDown = DBCountDown()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        fd_prefersNavigationBarHidden = true;
        
        initUI()
        bindEvent()
    }
    
    func initUI() {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(DBScreenWidth)
        }
        
        let backBtn = UIButton()
        scrollView.addSubview(backBtn)
        backBtn.setImage(UIImage(named: "nav_back"), for: .normal)
        backBtn.rx.tap.subscribe(onNext: { [weak self] in
            self?.back()
        }).disposed(by: disposeBag)
        backBtn.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(DBTopSafeHeight+12)
            make.width.height.equalTo(20)
        }
        
        let logoImgView = UIImageView()
        scrollView.addSubview(logoImgView)
        logoImgView.image = UIImage(named: "login_logo")
        logoImgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(backBtn.snp.bottom).offset(52)
        }
        
        let mainLabel = UILabel()
        scrollView.addSubview(mainLabel)
        mainLabel.textColor = DBTextColor
        mainLabel.font = DBFuturaMaxiStd_DemiFont(18)
        mainLabel.text = "Gabung Dana Bank"
        mainLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(logoImgView.snp.bottom).offset(20)
        }
        
        let phoneBgView = UIView()
        scrollView.addSubview(phoneBgView)
        phoneBgView.layer.cornerRadius = 2
        phoneBgView.backgroundColor = DBHexColor("#F6F6F6")
        phoneBgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(mainLabel.snp.bottom).offset(40)
            make.width.equalTo(DBScreenWidth - 40)
            make.height.equalTo(100)
        }
        
        let phoneTipLabel = UILabel()
        phoneBgView.addSubview(phoneTipLabel)
        phoneTipLabel.textColor = DBHexColor("B1BEB5")
        phoneTipLabel.font = DBFuturaMaxiStd_BookFont(12)
        phoneTipLabel.text = "Nomor Telepon"
        phoneTipLabel.snp.makeConstraints { make in
            make.left.top.equalTo(15)
        }
        
        let phoneTypeLabel = UILabel()
        phoneBgView.addSubview(phoneTypeLabel)
        phoneTypeLabel.textColor = DBViewBgColor
        phoneTypeLabel.font = DBFuturaMaxiStd_DemiFont(14)
        phoneTypeLabel.text = "+62"
        phoneTypeLabel.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(54)
        }
        
        let phoneLineView = UIView()
        phoneBgView.addSubview(phoneLineView)
        phoneLineView.backgroundColor = DBHexColor("B1BEB5")
        phoneLineView.snp.makeConstraints { make in
            make.left.equalTo(47)
            make.top.equalTo(57)
            make.height.equalTo(12)
            make.width.equalTo(1)
        }
        
        phoneBgView.addSubview(phoneTextField)
        phoneTextField.snp.makeConstraints { make in
            make.left.equalTo(56)
            make.top.equalTo(54)
            make.height.equalTo(18)
            make.right.equalTo(-15)
        }
        
        let phoneBottomLineView = UIView()
        phoneBgView.addSubview(phoneBottomLineView)
        phoneBottomLineView.backgroundColor = DBHexColor("#EDEDED")
        phoneBottomLineView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.bottom.equalTo(-15)
            make.height.equalTo(1)
        }
        
        let codeBgView = UIView()
        scrollView.addSubview(codeBgView)
        codeBgView.layer.cornerRadius = 2
        codeBgView.backgroundColor = DBHexColor("#F6F6F6")
        codeBgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(phoneBgView.snp.bottom).offset(24)
            make.width.equalTo(DBScreenWidth - 40)
            make.height.equalTo(100)
        }
        
        let codeTipLabel = UILabel()
        codeBgView.addSubview(codeTipLabel)
        codeTipLabel.textColor = DBHexColor("B1BEB5")
        codeTipLabel.font = DBFuturaMaxiStd_BookFont(12)
        codeTipLabel.text = "Kode Verifikasi"
        codeTipLabel.snp.makeConstraints { make in
            make.left.top.equalTo(15)
        }
        
        
        codeBgView.addSubview(codeTextField)
        codeTextField.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(54)
            make.height.equalTo(18)
            make.right.equalTo(-120)
        }
        
        
        codeBgView.addSubview(sendVerifyCodeBtn)
        sendVerifyCodeBtn.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.centerY.equalTo(codeTextField)
            make.height.equalTo(18)
            make.width.equalTo(80)
        }
        
        let codeBottomLineView = UIView()
        codeBgView.addSubview(codeBottomLineView)
        codeBottomLineView.backgroundColor = DBHexColor("#EDEDED")
        codeBottomLineView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.bottom.equalTo(-15)
            make.height.equalTo(1)
        }
        
        scrollView.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { make in
            make.top.equalTo(codeBgView.snp.bottom).offset(40)
            make.left.equalTo(20)
            make.height.equalTo(48)
            make.width.equalTo(DBScreenWidth - 40)
        }
        
        let agreeBgView = UIView()
        scrollView.addSubview(agreeBgView)
        agreeBgView.snp.makeConstraints { make in
            make.top.equalTo(loginBtn.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
            make.left.greaterThanOrEqualTo(20)
            make.right.greaterThanOrEqualTo(-20)
        }
        
        agreeBgView.addSubview(agreeBtn)
        agreeBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        agreeBgView.addSubview(agreeLabel)
        agreeLabel.snp.makeConstraints { make in
            make.top.equalTo(2)
            make.left.equalTo(agreeBtn.snp.right).offset(2)
            make.right.height.equalToSuperview()
        }
        
    }
    
    func bindEvent() {
        
        agreeBtn.rx.tap.subscribe(onNext: { [weak self] in
            self?.agreeBtn.isSelected.toggle()
            
            if (self?.agreeBtn.isSelected ?? false) &&
                (self?.phoneTextField.text?.count ?? 0 > 0) &&
                (self?.codeTextField.text?.count ?? 0 > 0)  {
                self?.loginBtn.isEnabled = true
            } else {
                self?.loginBtn.isEnabled = false
            }
            
        }).disposed(by: disposeBag)
        
        let phoneTextFieldObservable = phoneTextField.rx.text.orEmpty.map { !$0.isEmpty }
        let codeTextFieldObservable = codeTextField.rx.text.orEmpty.map { !$0.isEmpty }
        
        Observable.combineLatest(phoneTextFieldObservable, codeTextFieldObservable)
            .map {[weak self]  phoneTextFieldNotEmpty, codeTextFieldNotEmpty in
                return phoneTextFieldNotEmpty && codeTextFieldNotEmpty && (self?.agreeBtn.isSelected ?? false)
            }
            .bind(to: loginBtn.rx.isEnabled)
            .disposed(by: disposeBag)
        
        sendVerifyCodeBtn.rx.tap.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.requestSendCode()
            
        }).disposed(by: disposeBag)
        
        loginBtn.rx.tap.subscribe(onNext: { [weak self] in
            guard let self = self else { return }
            self.requestLogin()
            
        }).disposed(by: disposeBag)
        
        
        codeTextField.rx.controlEvent(.editingChanged).subscribe(onNext: { [weak self] in
            guard let self = self, let text = self.codeTextField.text else { return }
            if text.count > 6 {
                let endIndex = text.index(text.startIndex, offsetBy: 6)
                self.codeTextField.text = String(text[text.startIndex..<endIndex])
                
            }
            if (self.phoneTextField.text?.count ?? 0) > 0 &&
                self.codeTextField.text?.count == 6 &&
                self.agreeBtn.isSelected {
                self.requestLogin()
            }
        }).disposed(by: disposeBag)
        
    }
    
    
    func requestSendCode(){
        
        view.endEditing(true)
        
        guard let phone = self.phoneTextField.text else {
            return
        }
        
        let dic: [String: Any] = ["starin":phone,
                                  "jimmies":DBRandomString(),
                                  "hollered":DBRandomString()
                                  
        ]
        
        DBToast.showLoading(text: nil, toView: DBKeyWindow)
        
        DBNetworkTool.request(method: .post, urlString: Login_Send_Code, params: dic) { [weak self] baseModel in
            guard let self = self else {return}
            DBToast.hideFrom(view: DBKeyWindow)
            
            if baseModel.glared == 0 {
                self.sendVerifyCodeBtn.isEnabled = false
                self.countDown.fire()
                    .bind(to: self.sendVerifyCodeBtn.rx.title(for: .normal))
                    .disposed(by: self.disposeBag)
                self.countDown.isRunning.observe(on: MainScheduler.instance).subscribe { isRun in
                    if !isRun {
                        self.sendVerifyCodeBtn.isEnabled = true
                    }
                }.disposed(by: self.disposeBag)
                self.codeTextField.becomeFirstResponder()
            }
        } failed: { error in
            
            DBToast.hideFrom(view: DBKeyWindow)
        }
    }
    
    func requestLogin() {
        view.endEditing(true)
        
        guard let phone = self.phoneTextField.text else {
            return
        }
        
        guard let code = self.codeTextField.text else {
            return
        }
        
        let dic: [String: Any] = ["write":phone,
                                  "dutifully":code,
                                  "yucked":DBRandomString(),
                                  "fart":DBRandomString()
                                  
        ]
        
        DBToast.showLoading(text: nil, toView: DBKeyWindow)
        
        DBNetworkTool.request(method: .post, urlString: Login_URL, params: dic) { [weak self] baseModel in
            guard let self = self else {return}
            DBToast.hideFrom(view: DBKeyWindow)
            
            if baseModel.glared == 0 {
                
                guard let data = baseModel.signature as? [String: Any] else {
                    return
                }
                
                guard let session = data["grapevine"] as? String else {
                    return
                }
                //96615631c7b5cbc774c1e9b7db61e7f1
                UserDefaults.standard.setValue(session, forKey: DBSessionIDKey)
                UserDefaults.standard.setValue(phone, forKey: DBPhoneKey)
                UserDefaults.standard.synchronize()
                self.back()
                
            }
        } failed: { error in
            
            DBToast.hideFrom(view: DBKeyWindow)
        }
    }
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .white
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentInset = .zero
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return scrollView
    }()
    
    private lazy var phoneTextField: UITextField = {
        let phoneTextField = UITextField()
        phoneTextField.backgroundColor = .clear
        phoneTextField.font = DBFuturaMaxiStd_DemiFont(14)
        phoneTextField.textColor = DBTextColor
        phoneTextField.text = "12345"
        phoneTextField.leftViewMode = .always
        phoneTextField.keyboardType = .phonePad
        let att = NSMutableAttributedString(string: "Enter your cellphone number", attributes: [.foregroundColor:DBHexColor("#B1BEB5") ?? .gray, .font: DBFuturaMaxiStd_BookFont(14)])
        phoneTextField.attributedPlaceholder = att
        phoneTextField.tintColor = DBTextColor
        phoneTextField.clearButtonMode = .always
        return phoneTextField
    }()
    
    private lazy var codeTextField: UITextField = {
        let codeTextField = UITextField()
        codeTextField.backgroundColor = .clear
        codeTextField.font = DBFuturaMaxiStd_DemiFont(14)
        codeTextField.textColor = DBTextColor
        codeTextField.text = "12345"
        codeTextField.leftViewMode = .always
        codeTextField.keyboardType = .phonePad
        let att = NSMutableAttributedString(string: "Enter your code", attributes: [.foregroundColor:DBHexColor("#B1BEB5") ?? .gray, .font: DBFuturaMaxiStd_BookFont(14)])
        codeTextField.attributedPlaceholder = att
        codeTextField.tintColor = DBTextColor
        codeTextField.clearButtonMode = .always
        //        phoneTextField.delegate = self
        //        phoneTextField.addTarget(<#T##target: Any?##Any?#>, action: <#T##Selector#>, for: <#T##UIControl.Event#>)
        return codeTextField
    }()
    
    private lazy var sendVerifyCodeBtn: UIButton = {
        let sendVerifyCodeBtn = UIButton()
        sendVerifyCodeBtn.titleLabel?.font = DBFuturaMaxiStd_BookFont(14)
        sendVerifyCodeBtn.setTitle("send code", for: .normal)
        sendVerifyCodeBtn.setTitleColor(DBViewBgColor, for: .normal)
        
        return sendVerifyCodeBtn
    }()
    
    private lazy var loginBtn: UIButton = {
        let loginBtn = UIButton()
        loginBtn.titleLabel?.font = DBFuturaMaxiStd_BookFont(14)
        loginBtn.setTitle("Memasuki", for: .normal)
        loginBtn.setTitleColor(DBHexColor("#CCFF00"), for: .normal)
        loginBtn.setTitleColor(DBHexColor("#FFFFFF"), for: .disabled)
        loginBtn.setBackgroundImage(UIImage.imageWithColor(color: DBViewBgColor ?? UIColor.green), for: .normal)
        loginBtn.setBackgroundImage(UIImage.imageWithColor(color: DBHexColor("#B1BEB5") ?? UIColor.gray), for: .disabled)
        loginBtn.layer.cornerRadius = 2
        //        loginBtn.isEnabled = true
        return loginBtn
    }()
    
    private lazy var agreeBtn: UIButton = {
        let agreeBtn = UIButton()
        agreeBtn.setImage(UIImage(named: "login_agree_unselected"), for: .normal)
        agreeBtn.setImage(UIImage(named: "login_agree_selected"), for: .selected)
        //        agreeBtn.isSelected = true
        return agreeBtn
    }()
    
    private lazy var agreeLabel: YYLabel = {
        let agreeLabel = YYLabel()
        agreeLabel.numberOfLines = 0
        agreeLabel.preferredMaxLayoutWidth = DBScreenWidth - 62
        let agreeTipString = "I have read and agree"
        let privacyString = "Privacy Agreement"
        let agreeString = agreeTipString + " " + privacyString
        let att = NSMutableAttributedString(string: agreeString)
        att.font = DBFuturaMaxiStd_BookFont(11)
        att.color = DBHexColor("#B1BEB5")
        att.setTextHighlight(NSMakeRange(agreeTipString.count + 1, privacyString.count), color: DBViewBgColor, backgroundColor: .clear) { containerView, text, range, rect in
            DBLog("privacyString")
        }
        agreeLabel.attributedText = att
        return agreeLabel
    }()
    
    
}
